package cn.xy.base.server.aspect;

import cn.hutool.core.date.DateUtil;
import cn.xy.base.server.po.SysImportLog;
import cn.xy.base.server.service.SysImportLogService;
import cn.xy.base.server.web.AdminWebContext;
import cn.xy.commons.annotation.ImportLog;
import cn.xy.commons.constant.Consts;
import cn.xy.commons.core.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 导入日志切面
 *
 *  @author xy
 */
@Slf4j
@Aspect
@Component
public class ImportLogAspect {
    private final ThreadLocal<SysImportLog> logLocal = new ThreadLocal<>();

    @Autowired
    private SysImportLogService sysImportLogService;

    @Pointcut("execution(public * *..*.admapi..*.*(..))")
    public void sysImportLog() {
        // empty function
    }

    @Before("sysImportLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Map<String, String[]> paramsMap = request.getParameterMap();
        String urlPath = "";
        for (Map.Entry<String, String[]> entry : paramsMap.entrySet()) {
            urlPath = entry.getValue()[0];
        }
        String methodName = joinPoint.getSignature().getName();
        Method method = currentMethod(joinPoint, methodName);
        if (method == null) {
            return;
        }
        ImportLog importLog = method.getAnnotation(ImportLog.class);
        if (importLog != null) {
            SysImportLog sysImportLog = new SysImportLog();
            sysImportLog.setUserId(AdminWebContext.getAdminId());
            sysImportLog.setModule(importLog.module());
            sysImportLog.setUrlPath(urlPath);
            sysImportLog.setCreateTime(DateUtil.date());
            logLocal.set(sysImportLog);
        }
    }

    @AfterReturning(returning = "ret", pointcut = "sysImportLog()")
    public void doAfterReturning(Object ret) {
        SysImportLog sysImportLog = logLocal.get();
        if (sysImportLog != null && ret instanceof Result) {
            Result<?> result = (Result<?>) ret;
            sysImportLog.setStatus(result.getCode() == Consts.SUCCESS_CODE ? 1 : 0);
            sysImportLog.setResult(result.toString());
            sysImportLogService.save(sysImportLog);
        }
        logLocal.remove();
    }

    private Method currentMethod(JoinPoint joinPoint, String methodName) {
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }
}
